package com.kx.center.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.entity.Allocation;
import com.kx.center.entity.AllocationDetail;
import com.kx.center.entity.Store;
import com.kx.center.entity.query.QueryAllocation;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.exception.InventoryShortageException;
import com.kx.center.service.AllocationService;
import com.kx.center.service.StoreService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/allocation")
public class AllocationController {

	@Autowired
	AllocationService service;

	@Autowired
	StoreService storeService;

	@RequestMapping(value = "list/{store}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String list(HttpServletRequest request, @PathVariable("store") Integer store) throws Exception {
		
		Integer page, pageSize, status, fromStore, toStore;
		Date from = null, to = null;
		
		QueryAllocation query = new QueryAllocation();

		String fromStoreStr = request.getParameter("fromStore");
		String toStoreStr = request.getParameter("toStore");
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");
		
		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");
		
		status = NumberUtils.toInt(request.getParameter("status"));
		page = NumberUtils.toInt(request.getParameter("page"));
		pageSize = NumberUtils.toInt(request.getParameter("pageSize"));
		
		if(DateUtil.isDate(fromStr))
			from = DateUtils.parseDate(fromStr, "yyyy-MM-dd");

		if(DateUtil.isDate(toStr))
			to = DateUtils.parseDate(toStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");

		fromStore = NumberUtils.toInt(fromStoreStr);
		toStore = NumberUtils.toInt(toStoreStr);
		
		if(fromStore <= 0)
			fromStore = store;
		
		if(toStore <= 0)
			toStore = store;
		
		if(StringUtils.isBlank(sortBy))
			sortBy = "addtime";
		
		if(StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		query.setFrom(from);
		query.setTo(to);
		query.setStatus(status);
		query.setPage(page);
		query.setPageSize(pageSize);
		query.setSortBy(sortBy);
		query.setSortMethod(sortMethod);
		
		QueryResult result = service.queryAllocation(query);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	@RequestMapping(value = "detail/{aid}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String detail(HttpServletRequest request, @PathVariable("aid") Integer allocationId) throws Exception {

		if (allocationId != null && allocationId > 0) {
			List<AllocationDetail> list = service.findAllocationDetailByAllocationId(allocationId);

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("data", list);
			return Response.success(map);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}
	}

	@RequestMapping(value = "storeList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String storeList() throws Exception {

		List<Store> list = storeService.findAllStore();

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("data", list);
		return Response.success(map);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request) {
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");
		String allocationIdStr = request.getParameter("allocation_id");

		String json = request.getParameter("data");

		Integer allocationId = 0, from = 0, to = 0;

		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

		try {
			data = (ArrayList<HashMap<String, Object>>) JSONParser.parse(json, data.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}

		if (allocationIdStr != null && NumberUtils.isDigits(allocationIdStr)) {
			allocationId = NumberUtils.toInt(allocationIdStr);
		}

		if (fromStr != null && NumberUtils.isDigits(fromStr)) {
			from = NumberUtils.toInt(fromStr);
		}

		if (toStr != null && NumberUtils.isDigits(toStr)) {
			to = NumberUtils.toInt(toStr);
		}

		if (allocationId <= 0 && (from <= 0 || to <= 0))
			return Response.error(MessageCode.PARAMETER_WRONG);

		try
		{
			service.saveAllocation(from, to, allocationId, data);
			return Response.success("调拨单提交成功");
		} catch (InventoryShortageException ex) {
			return Response.error(MessageCode.INVENTORY_SHORTAGE, ex.getMessage());
		}

	}

	@RequestMapping(value = "{aid}/confirm", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String confirm_order(HttpServletRequest request, @PathVariable("aid") Integer allocationId) {

		if (allocationId <= 0) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			Allocation allocation = service.findAllocationById(allocationId);

			if (allocation == null)
				return Response.error(MessageCode.ALLOCATION_ID_WRONG);
			else {
				if (allocation.getStatus() != 1)
					return Response.error(MessageCode.OPERATOR_FAIL);
				else {
					try {
						service.confirm(allocation);
						return Response.success();
					} catch (InventoryShortageException ex) {
						return Response.error(MessageCode.INVENTORY_SHORTAGE, ex.getMessage());
					}
				}
			}
		}
	}
}
